/**
 * 清理环境脚本
 */
import { join } from 'path';
import { rm, readdir } from 'fs/promises';
const PACKAGES_PATH = 'packages';
const APPS_PATH = 'apps';
const DIRS = ['.nx', 'lib', 'cdn', 'types', 'dist', 'coverage', 'temp', '.vscode'];
const FILES = ['tsconfig.tsbuildinfo', 'package-lock.json', 'pnpm-lock.yaml'];

async function getPackages(dir) {
  return await readdir(dir);
}

/**
 * 清理文件夹
 * @param {*} list 文件夹下文件列表
 * @param {*} parentPath 文件夹路径
 */
async function cleanDir(list, parentPath) {
  for (let pkg of list) {
    console.log('cleanDir pkg:', pkg);
    for (let dir of DIRS) {
      const dirpath = join(parentPath, pkg, dir);
      console.log('cleanDir dirpath:', dirpath);
      await rm(dirpath, { recursive: true, force: true });
    }
    for (let file of FILES) {
      const filepath = join(parentPath, pkg, file);
      console.log('cleanDir filepath:', filepath);
      await rm(filepath, { recursive: true, force: true });
    }
  }
  await rm('node_modules', { recursive: true, force: true });
  for (let file of FILES) {
    console.log('cleanDir file:', file);
    await rm(file, { recursive: true, force: true });
  }
}

/**
 * 清理其他文件/文件夹
 */
async function cleanOther() {
  await rm('.nx', { recursive: true, force: true });
}

console.log('开始清理...');
await cleanDir(await getPackages(PACKAGES_PATH), PACKAGES_PATH);
await cleanDir(await getPackages(APPS_PATH), APPS_PATH);
await cleanOther();
console.log('清理完成！');
